/**
 @Name：layuiAdmin iframe版主入口
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
 */
document.domain = 'xiujiadian.com';

layui.extend({
    setter: 'config',   //配置模块
    admin: 'lib/admin', //核心模块
    view: 'lib/view',    //视图渲染模块
}).define(['setter', 'admin'], function (exports) {
    function _urlEncodeArr (data) {
        var urlEncode = function (param, key, encode) {
            if (param==null) return '';
            var paramStr = '';
            var t = typeof (param);
            if (t === 'string' || t === 'number' || t === 'boolean') {
                paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param);
            } else {
                for (var i in param) {
                    var k = key == null ? i : key + (param instanceof Array ? '' : '.' + i);
                    paramStr += urlEncode(param[i], k, encode)
                }
            }
            return paramStr;
        }

        return urlEncode(data).slice(1);
    }

    var setter = layui.setter,
        element = layui.element,
        admin = layui.admin,
        tabsPage = admin.tabsPage,
        view = layui.view,
        layer = layui.layer,
        zmnUtils = {
            getQueryParams: function (url) {
                var r = url ? url.split('?')[1] : window.location.search.substr(1);
                var params = {};
                if (r && r.length) {
                    var arr = r.split('&');
                    arr.forEach((item) => {
                        var ar = item.split('=');
                        params[decodeURIComponent(ar[0])] = decodeURIComponent(ar[1]);
                    });
                }

                return params;
            },
            serializeURL: function (url, params) {

                return url + '?' + _urlEncodeArr(params);
            }
        },
        //打开标签页
        openTabsPage = function (url, text) {
            //遍历页签选项卡
            var matchTo
                , tabs = $('#LAY_app_tabsheader>li')
                , path = url.replace(/(^http(s*):)|(\?[\s\S]*$)/g, '');

            // Tab 多开
            if (setter.whiteListOfMultiTab.includes(url)) {
                let params = zmnUtils.getQueryParams(url);
                params.t = Date.now();
                url = zmnUtils.serializeURL(url, params);
            }

            tabs.each(function (index) {
                var li = $(this)
                    , layid = li.attr('lay-id');

                if (layid === url) {
                    matchTo = true;
                    tabsPage.index = index;
                }
            });

            text = text || '新标签页';

            if (setter.pageTabs) {
                //如果未在选项卡中匹配到，则追加选项卡
                if (!matchTo) {
                    $(APP_BODY).append([
                        '<div class="layadmin-tabsbody-item layui-show">'
                        , '<iframe src="' + url + '" frameborder="0" class="layadmin-iframe"></iframe>'
                        , '</div>'
                    ].join(''));
                    tabsPage.index = tabs.length;
                    element.tabAdd(FILTER_TAB_TBAS, {
                        title: '<span>' + text + '</span>'
                        , id: url
                        , attr: path
                    });
                } else {
                    var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                    var params = zmnUtils.getQueryParams(url);
                    params.t = Date.now();
                    iframe[0].contentWindow.location.href = zmnUtils.serializeURL(url.split('?')[0], params);
                }
            } else {
                var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                iframe[0].contentWindow.location.href = url;
            }

            //定位当前tabs
            element.tabChange(FILTER_TAB_TBAS, url);
            admin.tabsBodyChange(tabsPage.index, {
                url: url
                , text: text
            });
        }

        , refreshAndCloseTabs = function (refreshUrl, closeUrl) {
            //遍历页签选项卡
            var matchTo,
                mathCloseIndex,
                mathCloseTo,
                tabs = $('#LAY_app_tabsheader>li'),
                path = refreshUrl.replace(/(^http(s*):)|(\?[\s\S]*$)/g, '');

            tabs.each(function (index) {
                var li = $(this), layid = li.attr('lay-id');
                if (layid === refreshUrl) {
                    matchTo = true;
                    tabsPage.index = index;
                }
                if (layid == closeUrl) {
                    mathCloseTo = true;
                    mathCloseIndex = index;
                }
            });

            if (mathCloseTo) {
                $('#LAY_app_tabsheader>li').eq(mathCloseIndex).find('.layui-tab-close').trigger('click');
            }

            if (matchTo) {
                //定位当前tabs
                element.tabChange(FILTER_TAB_TBAS, refreshUrl);
                admin.tabsBodyChange(tabsPage.index,
                    {
                        url: refreshUrl,
                        //text: text
                    });
                var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                // iframe[0].contentWindow.location.href = refreshUrl;
                iframe[0].contentWindow.location.reload();
            } else {
                console.log("调用openTabsPageRefresh没有匹配到url:", refreshUrl, "路径！");
            }
        }

        , APP_BODY = '#LAY_app_body', FILTER_TAB_TBAS = 'layadmin-layout-tabs'
        , $ = layui.$, $win = $(window);

    //初始
    if (admin.screen() < 2) admin.sideFlexible();

    //将模块根路径设置为 controller 目录
    layui.config({
        //base: setter.base + 'modules/'
        base: '/static/js/module/'
    });

    //扩展 lib 目录下的其它模块
    layui.each(setter.extend, function (index, item) {
        var mods = {};
        mods[item] = '{/}' + setter.base + 'lib/extend/' + item;
        layui.extend(mods);
    });

    view().autoRender();

    //加载公共模块
    layui.use('zmn.common');
    layui.extend({
        zmnApp: "zmn.app.common",
    }).use(['zmnApp']);

    //对外输出
    exports('index', {
        openTabsPage: openTabsPage
        , refreshAndCloseTabs: refreshAndCloseTabs
    });
});
